﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewBag.Title = "Bom添加";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bom工单</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 10px;
        }
        /* 表单行样式 */
        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 10px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
        }
        /* 标签样式 */
        label {
            width: 120px; /* 统一标签宽度 */
            text-align: right;
            margin-right: 10px;
            white-space: nowrap; /* 防止字段名换行 */
        }
        /* 输入框样式 */
        input {
            width: 200px; /* 修改输入框宽度为350px */
        }
        /* 文本域样式 */
        textarea {
            width: 350px;
            min-height: 50px; /* 设置文本域最小高度 */
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn" id="saveButton">保存</button>
        </div>
        <!-- 表单信息 -->
        <div class="form-row">
            <label>BOM编号:</label>
            <input type="text" id="bomCode" disabled placeholder="后端自动生成">
            <label>BOM主题:</label>
            <input type="text" id="bomTheme" placeholder="请输入主题">
        </div>
        <div class="form-row">
            <label>默认BOM:</label>
            <select id="documentCode">
                <option value="是">是</option>
                <option value="否">否</option>
            </select>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp &nbsp &nbsp;&nbsp;
            <label>版本:</label>
            <input type="text" id="bomVersion" placeholder="请输入版本">
        </div>
        <div class="form-row">
            <label>成品类型:</label>
            <select id="productType">
                <option value="类型一">类型一</option>
                <option value="类型二">类型二</option>
                <option value="类型三">类型三</option>
            </select>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;
            <label>成品名称:</label>
            <select id="productName">

            </select>
        </div>
        <div class="form-row">
            <label>日产量:</label>
            <input type="text" id="ProductionNum" placeholder="请输入日产量">
        </div>
        <div class="form-row">
            <label>备注:</label>
            <textarea id="remark"></textarea> <!-- 将备注改为文本域 -->
        </div>

        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            @* <button class="layui-btn layui-btn-xs" id="importButton">引入</button> *@
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
            <button class="layui-btn layui-btn-xs" id="addProcessButton">新增工序</button>
        </div>

        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>单位</th>
                    <th>品牌</th>
                    <th>配件数量</th>
                    <th>损耗率</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

        <!-- 工艺流程表格 -->
        <table class="layui-table" id="processTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>工序编码</th>
                    <th>工序名称</th>
                    <th>加工序号</th>
                    <th>工艺流程</th>
                    <th>负责人</th>
                    <th>部门</th>
                    <th>单位工作量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <script type="text/html" id="materialListTemplate">
        <div style="padding: 10px;">
            <table class="layui-table" id="materialListTable">
                <thead>
                    <tr>
                        <th>物料编码</th>
                        <th>物料名称</th>
                        <th>型号规格</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </script>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>

        const productTypeSelect = document.getElementById('productType');
        const productNameSelect = document.getElementById('productName');

        const productOptions = {
            '类型一': ['lamp', 'tree', 'star'],
            '类型二': ['moon', 'sun', 'Jupiter'],
            '类型三': ['Mars', 'Venus', 'Saturn']
        };

        function updateProductNameOptions() {
            const selectedType = productTypeSelect.value;
            const options = productOptions[selectedType];

            productNameSelect.innerHTML = '';

            options.forEach(option => {
                const newOption = document.createElement('option');
                newOption.value = option;
                newOption.textContent = option;
                productNameSelect.appendChild(newOption);
            });
        }

        productTypeSelect.addEventListener('change', updateProductNameOptions);

        // 初始加载时更新选项
        updateProductNameOptions();

        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;
            var CurrentRowIndex;
            // 初始化一个空行 - 物料行
            function initEmptyMaterialRow() {
                return {
                    partsCode: '',
                    partsName: '',
                    partsType: '',
                    partsUnit: '',
                    partsBrand: 0,
                    partsNum: 0,
                    partsLoss: '',
                };
            }

            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyMaterialRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml =
                    `<tr data-index="${rowCount - 1}">
                         <td>
                             ${rowCount}
                         </td>
                         <td>
                              <input type="text" class="layui-input partsCode" value="${material.partsCode}" id="partsCode"  readonly>
                          </td>
                          <td>
                               <input type="text" class="layui-input partsName" value="${material.partsName}" id="partsName" placeholder="物料名称">
                                   <button type="button" class="layui-btn layui-btn-xs selectMaterialButton" data-rowIndex="' + rowIndex + '">选择</button>
                                 </td>
                                         <td>
                                                    <input type="text" class="layui-input" value="${material.partsType}" id="partsType" placeholder="型号规格">
                                         </td>
                                         <td>
                                         <select class="layui-select partsUnit" id="partsUnit">
                                          <option value="台" ${material.partsUnit === '台' ? 'selected' : ''}>台</option>
                                          <option value="箱" ${material.partsUnit === '箱' ? 'selected' : ''}>箱</option>
                                          <option value="瓶" ${material.partsUnit === '瓶' ? 'selected' : ''}>瓶</option>
                                          </select>
                                          </td>
                                           <td>
                                          <select class="layui-select partsBrand" id="partsBrand">
                                                          <option value="1" ${material.partsBrand === '五毒牌' ? 'selected' : ''}>五毒牌</option>
                                                          <option value="2" ${material.partsBrand === '混合牌' ? 'selected' : ''}>混合牌</option>
                                                  <option value="3" ${material.partsBrand === '清新牌' ? 'selected' : ''}>清新牌</option>
                                          </select>
                                         </td>

                                                                      <td>
                                                                         <input type="number" class="layui-input partsNum" id="partsNum" value="${material.partsNum}" placeholder="配件数量">
                                                                      </td>
                                                                      <td>
                                                                        <input type="text" class="layui-input partsLoss" id="partsLoss" value="${material.partsLoss}" placeholder="损耗率">
                                                                      </td>

                                                                      <td>
                                                                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button>
                                                                      </td>
                                                                </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }
            //物料弹出框
            function showMaterialList() {
                layer.open({
                    type: 1,
                    title: '选择物料',
                    area: ['800px', '500px'],
                    content: $('#materialListTemplate').html(), // 假设后面会创建一个物料清单模板
                    success: function (layero) {
                        // 调用接口获取物料数据
                        $.ajax({
                            //url: 'http://localhost:5234/api/Materials/GetMaterial_Basic',
                            url: "@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic",
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 0) {
                                    var materialList = res.data;
                                    var tableBody = $('#materialListTable tbody');
                                    tableBody.empty();
                                    materialList.forEach(function (material) {
                                        var row = $('<tr>');
                                        row.append($('<td>').text(material.material_code));
                                        row.append($('<td>').text(material.material_name));
                                        row.append($('<td>').text(material.model_specification));
                                        row.append($('<td>').html('<button class="layui-btn layui-btn-xs selectMaterialConfirm">确认</button>'));
                                        row.data('material', material);
                                        tableBody.append(row);
                                    });
                                    form.render();
                                } else {
                                    layer.msg(res.msg || '获取物料数据失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('请求失败: ' + error, { icon: 2 });
                                console.error(xhr.responseText);
                            }
                        });
                    }
                });
            }
            //选择按钮绑定点击事件
            $(document).on('click', '.selectMaterialButton', function () {
                var $this = $(this);
                var rowIndex = $this.closest('tr').data('index');//获取当前行的索引
                CurrentRowIndex = rowIndex;
                console.log("获取当前行的索引", CurrentRowIndex);
                showMaterialList();
            });
            //处理"确定选择"按钮后的回填操作
            $(document).on('click', '.selectMaterialConfirm', function () {
                var material = $(this).closest('tr').data('material');
                var currentRow = $('#materialTable tbody tr').eq(CurrentRowIndex); // 获取当前选中的表格行
                currentRow.find('#partsCode').val(material.material_code);
                currentRow.find('#partsName').val(material.material_name);
                currentRow.find('#partsType').val(material.model_specification);
                var unit = material.unit_of_measurement_name;
                currentRow.find('#calulate option').each(function () {
                    if ($(this).text() === unit) {
                        $(this).prop('selected', true);

                    }
                });
                form.render();
                layer.closeAll('page'); // 关闭物料清单弹窗
            });
            // 初始化一个空行 - 工序行
            function initEmptyProcessRow() {
                return {
                    ProcessCode: '',
                    StepName: '',
                    OrderCode: 0,
                    ProcessName: '',
                    ResName: '',
                    DepName: '',
                    Num: 0
                };
            }

            // 添加工序行
            function addProcessRow(process) {
                process = process || initEmptyProcessRow();
                var rowCount = $('#processTable tbody tr').length + 1;

                var rowHtml =
                    `<tr data-index="${rowCount - 1}">
                                                                    <td>
                                                                        ${rowCount}
                                                                    </td>
                                                                    <td>
                                                                        <input type="text" class="layui-input processCode" value="${process.ProcessCode}" id="processCode" placeholder="工序编码">
                                                                     </td>
                                                                     <td>
                                                                                   <input type="text" class="layui-input stepName" value="${process.StepName}" id="stepName" placeholder="工序名称">
                                                                     </td>
                                         <td>
                                            <input type="number" class="layui-input" value="${process.OrderCode}"        id="orderCode" placeholder="加工序号">
                                         </td>
                                         <td>
                                            <input type="text" class="layui-input" value="${process.ProcessName}"        id="processName" placeholder="工艺流程">
                                         </td>
                                         <td>
                                            <input type="text" class="layui-input" value="${process.ResName}"        id="resName" placeholder="负责人">
                                         </td>
                                         <td>
                                            <input type="text" class="layui-input" value="${process.DepName}" id="depName" placeholder="部门">
                                         </td>
                                         <td>
                                            <input type="number" class="layui-input" value="${process.Num}"    id="num" placeholder="单位工作量">
                                         </td>
                                                                      <td>
                                                                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteProcessButton">删除</button>
                                                                      </td>
                                                                </tr>`;

                $('#processTable tbody').append(rowHtml);
                form.render();
            }

            // 初始化一个空物料行
            addMaterialRow();

            // 初始化一个空工序行
            addProcessRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });

            // 新增工序按钮点击事件
            $('#addProcessButton').click(function () {
                addProcessRow();
            });

            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', {
                    yes: function (index) {
                        $tr.remove();
                        // 重新编号
                        $('#materialTable tbody tr').each(function (index) {
                            $(this).find('td:first').text(index + 1);
                        });
                        layer.close(index); // 关闭提示框
                    }
                });
            });

            // 删除工序按钮点击事件
            $(document).on('click', '.deleteProcessButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该工序吗？', {
                    yes: function (index) {
                        $tr.remove();
                        // 重新编号
                        $('#processTable tbody tr').each(function (index) {
                            $(this).find('td:first').text(index + 1);
                        });
                        layer.close(index); // 关闭提示框
                    }
                });
            });

            // 保存按钮点击事件
            $('#saveButton').click(function () {
                var currentUser = localStorage.getItem('userData');
                var currentDate = new Date();
                var formData = {
                    bomCode: $('#bomCode').val(),
                    defaultBom: $('#documentCode').val(),
                    productType: $('#productType').val(),
                    productName: $('#productName').val(),
                    remarks: $('#remark').val(),
                    productionNum: $('#ProductionNum').val(),
                    bomTheme: $('#bomTheme').val(),
                    bomVersion: $('#bomVersion').val(),
                    EstimatedCost: "8000",
                    createName: currentUser,
                    createDate: currentDate,
                    bomParts: [],
                    ProcessInfo: []
                };

                // 收集物料数据
                $('#materialTable tbody tr').each(function () {
                    var $tr = $(this);
                    var material = {
                        bomCode: "2313",
                        partsCode: $tr.find('.partsCode').val(),
                        partsName: $tr.find('.partsName').val(),
                        partsType: $tr.find('#partsType').val(),    
                        partsUnit: $tr.find('.partsUnit').val(),
                        partsBrand: parseFloat($tr.find('.partsBrand').val()),
                        partsNum: parseFloat($tr.find('.partsNum').val()),
                        partsLoss: $tr.find('.partsLoss').val(),
                        
                    };
                    console.log(material)
                    formData.bomParts.push(material);
                });
                
                // 收集工序数据
                $('#processTable tbody tr').each(function () {
                    var $tr = $(this);
                    var process = {
                        ProcessCode: $tr.find('.processCode').val(),
                        StepName: $tr.find('.stepName').val(),
                        OrderCode: parseInt($tr.find('#orderCode').val()),
                        ProcessName: $tr.find('#processName').val(),
                        ResName: $tr.find('#resName').val(),
                        DepName: $tr.find('#depName').val(),
                        Num: parseInt($tr.find('#num').val())
                    };
                    console.log(process)
                    formData.ProcessInfo.push(process);
                });

                if (formData.bomParts.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }

                if (formData.ProcessInfo.length === 0) {
                    layer.msg('请至少添加一个工序', { icon: 2 });
                    return;
                }

                var loadIndex = layer.load(2);
                console.log("查看添加参数", formData);
                $.ajax({
                    //url: 'http://localhost:5090/api/WrokOrder/AddBom',
                    url: "@ViewBag.BaseUrl/T8/WrokOrder/AddBom",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 212) {
                            layer.msg(res.msg, { icon: 7 }, function () {
                                // 修正：这里应该是 res.id 而不是 formData.id
                                $('#documentCode').val(res.id);
                                location.href = "/WorkOrder/GetBOM";
                            });
                        } else {
                            layer.msg(res.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>